package com.qf.zuoye0613.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/13 18:57
 * @Version v1.8
 **/
@RestController
public class StuController {

    @PostMapping("/stu")
    public String addStudents(MultipartFile file) throws IOException {
        List<String> names = new ArrayList<>();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()))){
            String line;
            while ((line=bufferedReader.readLine())!=null){
                names.add(line.trim());
            }
        }

        if (names.isEmpty()){
            return "文件为空!";
        }

        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useSSL=false";
        String user = "root";
        String password = "1234";

        try {
            Connection conn = DriverManager.getConnection(url, user, password);
            String sql = "INSERT INTO student (name) VALUES (?)";
            PreparedStatement stmt = conn.prepareStatement(sql);
            for (String name : names){
                stmt.setString(1,name);
                stmt.executeUpdate();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "插入了"+names.size()+"个学生姓名";
    }
}
